import lodash from 'lodash';
import common from '../../../lib/common/common.js';
import {
    getPlayerData,
    getVegetableData,
    isPlayerExist,
    storagePlayerData,
    timestampToSeconds
} from '../l.js';

const REGULAR = /^(#|\/)?收[获菜]\*(\d+)/
export class Fs extends plugin {
    constructor() {
        super({
            name: '[Fs]收获',
            dsc: '收获',
            event: 'message',
            priority: 1,
            rule: [
                { reg: REGULAR, fnc: 'harvest' },
                { reg: /^(#|\/)?(一键|全部)收[获菜]$/, fnc: 'allHarvest' }
            ]
        })
    }
    async harvest(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply(['无玩家信息，请发送[领取田地]喵~'])
        }
        const [, , SERIAL_NUMBER] = e.msg.match(REGULAR)
        const PLAYER_DATA = await getPlayerData(PLAYER_ID)
        const VEGETABLE_INFO = PLAYER_DATA['frame'][SERIAL_NUMBER - 1]
        const VEGETABLE_DATA = await getVegetableData()
        const REMAINING_TIME = timestampToSeconds(Date.now()) - VEGETABLE_INFO['time']
        const CROP_DATA = VEGETABLE_DATA.find(c => c['name'] === VEGETABLE_INFO['name'])

        if (PLAYER_DATA['frame'].length < SERIAL_NUMBER) return e.reply(['你没有此格子，无法收获喵~'])
        if (!CROP_DATA) return e.reply(['数据报错，请联系BOT主人查询你存档信息喵~'])
        if (REMAINING_TIME < 0) return e.reply([`还未成熟，无法收获\r剩余${Math.abs(REMAINING_TIME)}秒喵~`])
        if (!VEGETABLE_INFO['start']) return e.reply(['该格子尚未种植喵~'])

        const RANDOM_NUMBER = lodash.random(1, 100)
        let multiple = 1
        let eventReminder = ''
        if (RANDOM_NUMBER === 1) {
            multiple = 5
            eventReminder = '触发概率事件大丰收!只有1%的概率,收获5倍作物'
        } else if (RANDOM_NUMBER < 10 && RANDOM_NUMBER > 1) {
            multiple = 2
            eventReminder = '触发概率事件丰收!收获2倍作物'
        }
        PLAYER_DATA['frame'][SERIAL_NUMBER - 1]['start'] = false
        if (!PLAYER_DATA['Stash'][VEGETABLE_INFO['name']]) {
            PLAYER_DATA['Stash'][VEGETABLE_INFO['name']] = { number: 0 }
        }
        if (!PLAYER_DATA['xp']) {
            PLAYER_DATA['xp'] = 0
        }
        PLAYER_DATA['xp'] += CROP_DATA['xp']
        let harvestAmount = CROP_DATA['harvest']
        if (VEGETABLE_INFO['fertilizer']) {
            const fertilizerEffect = {
                '普通化肥': 1.2,
                '高级化肥': 1.5,
                '特级化肥': 2
            }
            harvestAmount = Math.floor(harvestAmount * fertilizerEffect[VEGETABLE_INFO['fertilizer']])
        }
        PLAYER_DATA['Stash'][VEGETABLE_INFO['name']]['number'] += harvestAmount * multiple
        storagePlayerData(PLAYER_ID, PLAYER_DATA)

        const msg = [
            '收获成功!',
            `${eventReminder}`,
            `格子[${SERIAL_NUMBER}]`,
            `收获作物[${VEGETABLE_INFO['name']}]`,
            `数量[${harvestAmount * multiple}]`,
            VEGETABLE_INFO['fertilizer'] ? `使用了${VEGETABLE_INFO['fertilizer']}` : '',
            `获得XP[${CROP_DATA['xp']}]喵~`
        ].filter(Boolean).join('\r')
        return e.reply(msg)
    }

    async allHarvest(e) {
        const PLAYER_ID = e.user_id
        if (!isPlayerExist(PLAYER_ID)) {
            return e.reply(['无玩家信息，请发送[领取田地]喵~'])
        }
        const PLAYER_DATA = await getPlayerData(PLAYER_ID)
        const VEGETABLE_DATA = await getVegetableData()
        let msg = []
        for (let i = 0; i < PLAYER_DATA['frame'].length; i++) {
            const INFO = PLAYER_DATA['frame'][i]
            const CROP_DATA = VEGETABLE_DATA.find(c => c['name'] === INFO['name'])
            if (!INFO['start']) {
                msg.push(`格子[${i + 1}]暂未种植`)
                continue
            }
            if (timestampToSeconds(Date.now()) - INFO['time'] > 0) {
                const RANDOM_NUMBER = lodash.random(1, 100)
                let multiple = 1
                let eventReminder = ''
                if (RANDOM_NUMBER === 1) {
                    multiple = 5
                    eventReminder = '触发概率事件大丰收!只有1%的概率,收获5倍作物'
                } else if (RANDOM_NUMBER < 10 && RANDOM_NUMBER > 1) {
                    multiple = 2
                    eventReminder = '触发概率事件丰收!收获2倍作物'
                }

                PLAYER_DATA['frame'][i]['start'] = false
                if (!PLAYER_DATA['Stash'][INFO['name']]) {
                    PLAYER_DATA['Stash'][INFO['name']] = { number: 0 }
                }
                if (!PLAYER_DATA['xp']) {
                    PLAYER_DATA['xp'] = 0
                }
                PLAYER_DATA['xp'] += CROP_DATA['xp']
                let harvestAmount = CROP_DATA['harvest']
                if (INFO['fertilizer']) {
                    const fertilizerEffect = {
                        '普通化肥': 1.2,
                        '高级化肥': 1.5,
                        '特级化肥': 2
                    }
                    harvestAmount = Math.floor(harvestAmount * fertilizerEffect[INFO['fertilizer']])
                }
                PLAYER_DATA['Stash'][INFO['name']]['number'] += harvestAmount * multiple
                storagePlayerData(PLAYER_ID, PLAYER_DATA)

                msg.push([`${eventReminder}`,
                `格子[${i + 1}]`,
                `收获作物[${INFO['name']}]`,
                `数量[${harvestAmount * multiple}]`,
                INFO['fertilizer'] ? `使用了${INFO['fertilizer']}` : '',
                `获得XP[${CROP_DATA['xp']}]喵~`])
            } else {
                msg.push([
                    `格子[${i + 1}]`,
                    `作物[${INFO['name']}]还未成熟`
                ])
            }
        }

        return e.reply(await common.makeForwardMsg(e, msg, '收获信息'))
    }
}